﻿#include "MyTcpServer.h"

MyTcpServer::MyTcpServer()
{
}

MyTcpServer& MyTcpServer::getInstance()
{
	static MyTcpServer instance;
	return instance;
}

//服务器收到客户机的连接后执行
void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
	qDebug() << "new client connected";
	MyTcpSocket* pTcpSocket = new MyTcpSocket;
	pTcpSocket->setSocketDescriptor(socketDescriptor);
	m_tcpSocketList.append(pTcpSocket);

	connect(pTcpSocket, SIGNAL(offline(MyTcpSocket*)),
		this, SLOT(deleteSocket(MyTcpSocket*)));
}

void MyTcpServer::reSend(const char* perName, PDU* pdu) {
	if (perName == NULL || pdu == NULL) {
		return;
	}
	QString strPerName = QString(perName);
	for (int i = 0; i < m_tcpSocketList.size(); i++) {
		if (m_tcpSocketList.at(i)->getName() == strPerName) {
			m_tcpSocketList.at(i)->write((char*)pdu, pdu->uiPDULen);
			break;
		}
	}
}

void MyTcpServer::deleteSocket(MyTcpSocket* pTcpSocket) {
	QList<MyTcpSocket*>::iterator iter = m_tcpSocketList.begin();
	for (; iter != m_tcpSocketList.end(); iter++) {
		if (pTcpSocket == *iter) {
			//delete pTcpSocket;
			(*iter)->deleteLater();
			m_tcpSocketList.erase(iter);
			break;
		}
	}
	qDebug() << "余下socket目录：";
	for (iter = m_tcpSocketList.begin();
		iter != m_tcpSocketList.end(); iter++) {
		qDebug() << (*iter)->getName();
	}
	return;
}